package com.ww.grtsmanager.service.impl;

import com.ww.grtsmanager.bean.Chapter;
import com.ww.grtsmanager.bean.Course;
import com.ww.grtsmanager.bean.CourseDes;
import com.ww.grtsmanager.bean.CourseStatus;
import com.ww.grtsmanager.mapper.CourseDesMapper;
import com.ww.grtsmanager.mapper.CourseMapper;
import com.ww.grtsmanager.service.CourseService;
import com.ww.grtsmanager.vo.CourseInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseDesMapper courseDesMapper;
    @Transactional
    @Override
    public int addCourse(Course course, String des) {
        course.setBuyCount(0L);
        course.setViewCount(0L);
        course.setStatus(CourseStatus.Draft);
        Date date = new Date();
        course.setGmtCreated(date);
        course.setGmtModified(date);
        int i = courseMapper.addCourse(course);
        if (i==0){
            throw new RuntimeException("添加课程基本信息失败");
        }
        CourseDes courseDes = new CourseDes();
        //课程与课程描述是一对一关系
        courseDes.setId(course.getId());
        courseDes.setDes(des);
        courseDes.setGmtCreated(date);
        courseDes.setGmtModified(date);
        int j = courseDesMapper.addCourseDes(courseDes);
        if (j==0){
            throw new RuntimeException("添加课程描述信息失败");
        }
        return course.getId();
    }

    @Override
    public List<Chapter> getChapterAll(Integer courseId) {
        List<Chapter> list = courseMapper.getChapterAll(courseId);
        return list;
    }

    @Override
    public CourseInfo getCourse(Integer id) {
        CourseInfo courseInfo = courseMapper.getCourse(id);
        return courseInfo;
    }
    @Transactional
    @Override
    public void updateCourse(Course course, String des) {
        Date date = new Date();
        course.setGmtModified(date);
        int i = courseMapper.updateCourse(course);
        if (i==0){
            throw new RuntimeException("修改课程基本信息失败");
        }
        CourseDes courseDes = new CourseDes();
        courseDes.setId(course.getId());
        courseDes.setDes(des);
        courseDes.setGmtModified(date);
        int j = courseDesMapper.updateCourseDes(courseDes);
        if (j==0){
            throw new RuntimeException("修改课程描述信息失败");
        }
    }
}
